const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const { User } = require("./modules");
const Users = require("./data-sources/user");

const app = express();

const typeDefs = gql`
  type User {
    _id: ID!
    name: String!
    age: Int!
  }

  type Query {
    users: [User!]!
    user(id: ID!): User!
  }
`;

const resolvers = {
  Query: {
    users: async (_, args, { dataSources }) => {
      const users = await dataSources.users.getUsers();
      return users;
    },
    user: async (_, { id }, { dataSources }) => {
      const user = await dataSources.users.getUser(id);
      return user;
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources() {
    return {
      users: new Users(User),
    };
  },
});
server.applyMiddleware({ app });

app.use((req, res) => {
  res.status(200);
  res.send("Hello!");
  res.end();
});

app.listen(4000, () => {
  console.log(
    `Server is running on http://localhost:4000${server.graphqlPath}`
  );
});
